package com.yycx.module.bus.provider.handler.haiying.tasktodo.calculate;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.bus.client.entity.hy.BusHyorderReturn;
import com.yycx.module.bus.client.entity.hy.BusPaymentOrder;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.entity.hy.HyOrderDetail;
import com.yycx.module.bus.client.enums.HySaleTypeEnum;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.provider.handler.haiying.HyOrderDetailsSplit;
import com.yycx.module.bus.provider.service.hy.BusHyorderReturnService;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderDetailService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 费用核算申请结束监听器(临时备用，待老数据没了删除)
 *
 * @author zyf
 */
@Component
public class HySettleApplyProcessEndListener implements ExecutionListener {
    @Resource
    private HyOrderService orderService;
    @Resource
    private HyOrderDetailService hyOrderDetailService;
    @Resource
    private BusPaymentOrderService paymentOrderService;

    @Resource
    private BusHyorderReturnService hyorderReturnService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        //获取业务主键
        String businessKey = delegateExecution.getProcessInstanceBusinessKey();
        orderService.updateCaclulateOrder(businessKey, CommonConstants.INT_2);
        //添加回款记录
        insertOrderDetailsReturn(businessKey);
    }

    /**
     * 添加回款记录
     *
     * @param businessKey
     */
    private void insertOrderDetailsReturn(String businessKey) {
        HyOrder order = orderService.getById(businessKey);
        Integer sendType = order.getSendType();
        String orderType = order.getOrderType();

        //订单明细
        List<HyOrderDetail> orderDetailList = hyOrderDetailService.selectInsertToReturnList(businessKey);
        //销售订单
        if (HySaleTypeEnum.CHA.getCode().equals(orderType)) {
            if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                List<BusHyorderReturn> list = getList(orderDetailList);
                if (FlymeUtils.isNotEmpty(list)) {
                    for (BusHyorderReturn hyorderReturn : list) {
                        String orderDetailsId = hyorderReturn.getOrderDetailsId();
                        //查询是否存在回款明细
                        List<BusHyorderReturn> returnList = hyorderReturnService.getByOrderDetailsId(orderDetailsId);
                        if (FlymeUtils.isNotEmpty(returnList)) {
                            //size=1代表回款记录未被拆分直接覆盖更新
                            if (returnList.size() == 1) {
                                BusHyorderReturn old = returnList.get(0);
                                BeanUtil.copyProperties(hyorderReturn, old, CopyOptions.create().setIgnoreProperties("orderDetailsReturnId").ignoreNullValue());
                                hyorderReturn.setCreateTime(DateUtils.getNowDateTime());
                                hyorderReturnService.saveOrUpdate(old);
                            } else {
                                //size>1代表回款记录已经被拆分,需要按比例进行金额更新
                                hyorderReturnService.updateBusHyorderReturn(returnList, hyorderReturn);
                            }
                        } else {
                            //直接保存回款明细
                            hyorderReturnService.save(hyorderReturn);
                        }
                    }
                }

            }
            //现款或者预付款
            if (SendTypeEnum.XK.getCode().equals(sendType) || SendTypeEnum.YSK.getCode().equals(sendType)) {
                //回款明细
                List<BusPaymentOrder> paymentOrderList = paymentOrderService.selectByOrderIdOrderByAmountAsc(businessKey);
                List<BusHyorderReturn> result = HyOrderDetailsSplit.split(orderDetailList, paymentOrderList);
                hyorderReturnService.saveBatch(result);
            }
            //全额资信
            if (SendTypeEnum.QZ.getCode().equals(sendType)) {
                List<BusHyorderReturn> list = getList(orderDetailList);
                hyorderReturnService.saveBatch(list);
            }
        }
        //退货
        if (HySaleTypeEnum.CHC.getCode().equals(orderType)) {
            List<BusHyorderReturn> list = getList(orderDetailList);
            hyorderReturnService.saveBatch(list);
        }
    }

    /**
     * 构建回款明细
     *
     * @param orderDetailList
     * @return
     */
    private List<BusHyorderReturn> getList(List<HyOrderDetail> orderDetailList) {
        List<BusHyorderReturn> list = new ArrayList<>();
        for (HyOrderDetail hyOrderDetail : orderDetailList) {
            BusHyorderReturn orderReturn = new BusHyorderReturn();
            BeanUtils.copyProperties(hyOrderDetail, orderReturn);
            orderReturn.setOrderDetailsReturnId(IdWorker.getId());
            orderReturn.setOverStandAmount(new BigDecimal("0"));
            orderReturn.setOverDateAmount(new BigDecimal("0"));
            orderReturn.setCreateTime(DateUtils.getNowDateTime());
            orderReturn.setUpdateTime(null);
            list.add(orderReturn);
        }
        return list;
    }
}
